package com.duan.search.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.duan.entity.Result;
import com.duan.goods.feign.ProductFeign;
import com.duan.goods.pojo.Detail;
import com.duan.search.mapper.ESManagerMapper;
import com.duan.search.pojo.DetailIndex;
import com.duan.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esManagerMapper;

    //创建索引库结构
    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(DetailIndex.class);
        //创建映射
        elasticsearchTemplate.putMapping(DetailIndex.class);
    }

    //导入全部集合进入到索引库
    @Override
    public void importById(String id) {
        //获取access_token
        Map gettoken = new HashMap();
        gettoken.put("grant_type", "client_credentials");
        gettoken.put("client_id", "duan");
        gettoken.put("client_secret", "123456");
        String post = HttpUtil.post("http://localhost:9200/oauth/token", gettoken);
        Map map = JSONObject.parseObject(post, Map.class);
        String access_token = (String) map.get("access_token");
        //存储access_token
        Map header = new HashMap();
        header.put("Authorization","Bearer "+ access_token);
        //存储参数
        Map params = new HashMap();
        params.put("id",id);
        //获取数据
        String body = HttpUtil.createGet("http://localhost:9011/detail/findDetail").addHeaders(header).form(params).execute().body();
        //获取mysql中数据
        Detail detail = JSONObject.parseObject(JSONObject.parseObject(body, Result.class).getData().toString(), Detail.class);
//        Detail data = productFeign.findDetail(Long.valueOf(id)).getData();
        //转成索引类型对象并设置id
        String jsonString = JSON.toJSONString(detail);
        DetailIndex detailIndex = JSONObject.parseObject(jsonString, DetailIndex.class);
        //保存索引库
        esManagerMapper.save(detailIndex);
    }

    @Override
    public void deleteById(String id) {
        esManagerMapper.deleteById(id);
    }
}
